package com.kinroy.service;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author kinroy
 * @create 2024-09-26  16:14
 * @Description
 */
@Service
public class SocketServerService {
    private static final int PORT = 7070;

    @PostConstruct
    public void startSocketServer() {
        // 启动一个新线程来处理Socket
        new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(PORT)) {
                System.out.println("Socket服务器启动，等待客户端连接...");

                while (true) {
                    try (Socket clientSocket = serverSocket.accept()) {
                        System.out.println("客户端已连接: " + clientSocket.getInetAddress());

                        // 读取客户端发送的数据
                        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        StringBuilder receivedMessage = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            receivedMessage.append(line);
                        }
                        System.out.println("收到的报文: " + receivedMessage.toString());

                        // todo:生成 XML 响应报文
                        String responseXml = "";
                        System.out.println("生成的响应XML: " + responseXml);

                        // 分段发送响应报文
                        try (OutputStream outputStream = clientSocket.getOutputStream()) {
                            // todo: 分段发送，每次80字符，自己配一下
                            sendInChunks(responseXml, outputStream, 80);
                            System.out.println("已完成分段发送");
                        }
                    } catch (IOException e) {
                        System.err.println("客户端连接处理时出错: " + e.getMessage());
                    }
                }
            } catch (IOException e) {
                System.err.println("服务器启动失败: " + e.getMessage());
            }
        }).start();
    }
    private static void sendInChunks(String data, OutputStream outputStream, int chunkSize) throws IOException {
        int length = data.length();
        int offset = 0;
        // 分块发送
        while (offset < length) {
            int end = Math.min(offset + chunkSize, length);
            String chunk = data.substring(offset, end);
            outputStream.write(chunk.getBytes("UTF-8"));
            outputStream.flush();
            System.out.println("发送分段报文: " + chunk);
            offset = end;
            try {
                Thread.sleep(100); // 延迟100毫秒再发送下一块
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        outputStream.write("EOF".getBytes("UTF-8"));
        outputStream.flush();
    }
}
